package org.study.event.core.eventbus;

import java.util.List;

import org.study.event.core.common.EventMessage;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionHandler;

/***
 * 抽象类
 * 
 * @author 陈波
 *
 */
public abstract class AbstractGuavaEventBusManager implements EventBusManager {

	/***
	 * eventBus,子类来指定实现
	 */
	protected EventBus eventBus;

	protected String identifier;

	protected SubscriberExceptionHandler subscriberExceptionHandler;

	public void setIdentifier(String identifier) {
		this.identifier = identifier;
	}

	public void setSubscriberExceptionHandler(SubscriberExceptionHandler subscriberExceptionHandler) {
		this.subscriberExceptionHandler = subscriberExceptionHandler;
	}

	/**
	 * 消息订阅者
	 */
	private List<Object> subscribers;

	public List<Object> getSubscribers() {
		return subscribers;
	}

	public void setSubscribers(List<Object> subscribers) {
		this.subscribers = subscribers;
	}

	/***
	 * 注册订阅者
	 * 
	 * @param subscriber
	 */
	public void registerSubscriber(Object subscriber) {
		registerSubscriber(subscriber, true);
	}

	protected void registerSubscriber(Object subscriber, boolean addList) {
		eventBus.register(subscriber);
		if (addList) {
			this.subscribers.add(subscriber);
		}
	}

	public void unregister(Object subscriber) {
		eventBus.unregister(subscriber);
		if (this.subscribers != null) {
			this.subscribers.remove(subscriber);
		}
	}

	@Override
	public void postMessage(EventMessage message) {
		this.eventBus.post(message);
	}

	/***
	 * 初始化EventBus
	 */
	public abstract void initEventBus();

	/**
	 * 初始化管理器
	 */
	public void intEventBusManager() {
		initEventBus();
		registerSubscriber();
	}

	/***
	 * 初始完毕后完成注册操作
	 */
	private void registerSubscriber() {
		if (this.subscribers != null && this.subscribers.size() > 0) {
			for (Object subscriber : this.subscribers) {
				registerSubscriber(subscriber, false);
			}
		}
	}
}
